package com.jintoufs.web.action.tour;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.QueryRule;
import com.jintoufs.domain.constants.FullCalendar;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.tour.TourRoute;
import com.jintoufs.domain.tour.TourRouteDay;
import com.jintoufs.domain.tour.TourRoutePrice;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.tour.TourRouteService;
import com.jintoufs.service.travelagency.TravelAgencyService;
import com.jintoufs.util.date.DateUtils;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.apache.commons.lang.StringUtils;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author zhenghq
 * @date 2018-02-24 09:27
 */
@Controller
@Scope("prototype")
@RequestMapping("/tour/route")
public class TourRoutAction extends SupportAction{

    @Autowired
    TourRouteService tourRouteService;

    @Autowired
    TravelAgencyService travelAgencyService;

    /**
     * 线路管理列表页面
     */
    @RequestMapping("/list")
    public String list(Model model,String taId) {
        model.addAttribute("taId",taId);
        model.addAttribute("ta",travelAgencyService.getTravelAgencyById(taId));
        return "tour/route/list";
    }

    /**
     * 假期列表页面
     */
    @RequestMapping("/talist")
    public String travelAgencyList(Model model) {
        Map<String,Object> params = new HashMap<String,Object>();
//        params.put("managerId",customer.getId());
        model.addAttribute("tas",tourRouteService.getTravelAgencyListByParams(params));
        return "tour/route/talist";
    }

    /**
     * 查询线路信息
     */
    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(String taId, int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = StringUtils.isEmpty(filters)?new QueryFilters()
                : JSON.parseObject(filters, QueryFilters.class);
        if (!ValidUtil.isEmpty(taId)){
            QueryRule role = new QueryRule();
            role = new QueryRule();
            role.setOp("eq");
            role.setField("travel_agency_id");
            role.setData(taId);
            filters_.getRules().add(role);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String,Object>> list = tourRouteService.getByFilter(filters_);
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(), pageInfo.getList());
    }

    /**
     * 查看线路详情
     */
    @RequestMapping("/detail")
    @SystemControllerLog(description = "获取线路详情")
    public String detail(Model model, String routeId,String taId) {
        model.addAttribute("taId",taId);
        TourRoute route = tourRouteService.getRouteById(routeId);
        List<Map<String,Object>> trips = new LinkedList<>();
        List<TourRouteDay> days = tourRouteService.getRouteDaysByRouteId(routeId);
        for(TourRouteDay day:days){
            Map<String,Object> dayMap = new HashMap();
            dayMap.put("day",day);
            dayMap.put("activities",tourRouteService.getRouteDayDetailsByDayId(day.getId()));
            trips.add(dayMap);
        }
        model.addAttribute("route",route);
        model.addAttribute("trips",trips);
        Map<String,Object> params = new HashMap();
        //线路类型的 parent_id = 1005002
        params.put("parentId","1005002");
        model.addAttribute("typeList",tourRouteService.getTourRouteTypeInfo(params));
        return "tour/route/detail";
    }

    @RequestMapping("pricealendar")
    public String priceCalendar(String routeId,Model model){
        model.addAttribute("routeId",routeId);
        return "/tour/route/pricecalendar";
    }

    @RequestMapping("/getpricecalendar/{id}")
    public void getPriceCalendar(@PathVariable String id, String start, String end, HttpServletResponse response){
        Map<String,Object> param = new HashMap<>(1);
        param.put("tourRouteId",id);
        param.put("start",start);
        param.put("end",end);
        List<FullCalendar> priceCalendar = tourRouteService.getPriceCalendar(param);

        writeInfo(response,JSON.toJSONString(priceCalendar));
    }

    /**
     * 向客户端写数据
     *
     * @param response
     * @param info
     */
    @Override
    public void writeInfo(HttpServletResponse response, String info) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(info);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("setRecommend")
    @ResponseBody
    public AjaxMsg setRecommend(String id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            TourRoute scene= tourRouteService.selectByPrimaryKey(id);
            if("0".equals(scene.getRecommend())){
                scene.setRecommend("1");
            }else{
                scene.setRecommend("0");
            }
            tourRouteService.update(scene);
            ajaxMsg.setMessage("操作成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }

    @RequestMapping("notToGiveUp/{id}")
    @ResponseBody
    public AjaxMsg notToGiveUp(@PathVariable String id, String start){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String,Object> params = new HashMap<>();
        params.put("tourRouteId",id);
        params.put("start",start);
        try {
            TourRoutePrice tourRoutePrice = tourRouteService.getTourRoutePrice(params);
            if (ValidUtil.isEmpty(tourRoutePrice)){
                TourRoute tourRoute = tourRouteService.getRouteById(id);
                tourRoutePrice = new TourRoutePrice();
                tourRoutePrice.setId(getUUID());
                tourRoutePrice.setTourRouteId(id);
                tourRoutePrice.setPrice(tourRoute.getTotalFee());
                tourRoutePrice.setDistributionPrice(tourRoute.getDistributionPrice());
                tourRoutePrice.setTravelAgencyId(tourRoute.getTravelAgencyId());
                tourRoutePrice.setReserve(tourRoute.getPersonNum());
                tourRoutePrice.setStatus("0");
                tourRoutePrice.setDate(DateUtils.stringToDate(start));
                tourRouteService.insertTourRoutePrice(tourRoutePrice);
            }else {
                if ("1".equals(tourRoutePrice.getStatus())||ValidUtil.isEmpty(tourRoutePrice.getStatus())){
                    tourRoutePrice.setStatus("0");
                }else {
                    tourRoutePrice.setStatus("1");
                }
                tourRouteService.updateTourRoutePrice(tourRoutePrice);
            }
        }catch (Exception e){
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("出错啦！请稍后重试。");
        }
        return ajaxMsg;
    }
}
